<template>
  <div>
    <h2>任务列表</h2>
    <div>
      <el-select v-model="filter" @change="filterTasks">
        <el-option label="所有任务" value="all" />
        <el-option label="已完成" value="completed" />
        <el-option label="未完成" value="incomplete" />
      </el-select>
    </div>
    <ul>
      <li v-for="(task, index) in filteredTasks" :key="index">
        <el-checkbox v-model="task.completed" @change="updateTaskStatus(task)">
          {{ task.name }}
        </el-checkbox>
        <el-button type="danger" @click="removeTask(index)"> 删除 </el-button>
        <el-button @click="speakTask(index)">播放</el-button>
      </li>
    </ul>
  </div>
</template>

<script lang="ts">
import { onMounted, onBeforeMount, ref, computed } from 'vue'
import { useStore } from 'vuex'
import { Store } from 'vuex' // 导入 Store 类型

interface Task {
  name: string
  completed: boolean
}

export default {
  setup() {
    const store = useStore() as Store<{ allTasks: Task[] }> // 指定 store 类型
    const filter = ref<'all' | 'completed' | 'incomplete'>('all')
    const filteredTasks = ref<Task[]>([])
    const speech = ref({
      allVoices: [] as SpeechSynthesisVoice[],
      synth: window.speechSynthesis
    })

    onBeforeMount(() => {
      speech.value.allVoices = speech.value.synth.getVoices()
    })

    onMounted(() => {
      filteredTasks.value = allTasks.value
    })

    const allTasks = computed<Task[]>(() => store.getters.allTasks)

    const filterTasks = () => {
      if (filter.value === 'completed') {
        filteredTasks.value = allTasks.value.filter(task => task.completed)
      } else if (filter.value === 'incomplete') {
        filteredTasks.value = allTasks.value.filter(task => !task.completed)
      } else {
        filteredTasks.value = allTasks.value
      }
    }

    const updateTaskStatus = (task: Task) => {
      // 这里可以添加逻辑来更新任务状态
      // 例如，调用 Vuex 的 action 来更新状态
    }

    const speakTask = (index: number) => {
      if (typeof SpeechSynthesisUtterance !== 'undefined') {
        if (speech.value.allVoices.length > 0) {
          const voiceUtt = new SpeechSynthesisUtterance(allTasks.value[index].name)
          voiceUtt.voice =
            speech.value.allVoices.find(item => item.lang === 'zh-CN' && item.name.includes('(Natural)')) || null
          speech.value.synth.speak(voiceUtt)
        } else {
          console.log('speech:', speech.value)
        }
      }
    }

    const removeTask = (index: number) => {
      store.dispatch('removeTask', index)
    }

    return {
      filter,
      filteredTasks,
      filterTasks,
      updateTaskStatus,
      speakTask,
      removeTask
    }
  }
}
</script>
